package com.dc.datacollect.components.zip;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZIPUtils {
    public static void zipFiles(List<CompressFileWrap> fileWrapList, File zipfile) throws IOException {
        FileOutputStream fos = new FileOutputStream(zipfile);
        ZipOutputStream zos = new ZipOutputStream(fos);

        for (CompressFileWrap fileWrap : fileWrapList) {
            File file = fileWrap.getFile();
            String filename = fileWrap.getFilename();
            String path = fileWrap.getPath();

            if (file.isDirectory()) {
                zipDirectory(file, path, zos);
            } else {
                zipFile(file, filename, path, zos);
            }
        }

        zos.close();
        fos.close();
    }

    private static void zipDirectory(File directory, String path, ZipOutputStream zos) throws IOException {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // Recursively zip subdirectories
                    String subPath = path + "/" + file.getName();
                    zipDirectory(file, subPath, zos);
                } else {
                    // Zip files in the directory
                    zipFile(file, file.getName(), path, zos);
                }
            }
        }
    }

    private static void zipFile(File file, String filename, String path, ZipOutputStream zos) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        String name = file.getName();

        // Create a new ZIP entry with the specified path and filename
        ZipEntry zipEntry = new ZipEntry(path + "/" + filename+name.substring(name.lastIndexOf(".")));
        zos.putNextEntry(zipEntry);

        // Read from the input stream and write to the ZIP output stream
        byte[] buffer = new byte[1024];
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }

        // Close the current entry and input stream
        zos.closeEntry();
        fis.close();
    }
}
